Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Install Datasets and Upgrade TensorFlow

To ensure we can download the latest version of the oxford_flowers102 dataset, let's first install both tensorflow-datasets and tfds-nightly.

  • tensorflow-datasets is the stable version that is released on a cadence of every few months
  • tfds-nightly is released every day and has the latest version of the datasets

We'll also upgrade TensorFlow to ensure we have a version that is compatible with the latest version of the dataset.

In [1]:
%pip --no-cache-dir install tfds-nightly --user
%pip --no-cache-dir install --upgrade tensorflow --user
%pip --no-cache-dir install --upgrade tensorflow-datasets --user
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/ad/8d/0fdd4088fd28592c2dc39e54fc546774a096086e17c8d8e1d3d4c623fa87/tfds_nightly-4.6.0.dev202207290046-py3-none-any.whl (4.5MB)
     |████████████████████████████████| 4.5MB 5.0MB/s eta 0:00:01
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/c6/be/c553117f399613062c7ff4b370386d637df80b404fac7c4231497cdf83cc/protobuf-4.21.4-cp37-abi3-manylinux2014_x86_64.whl (408kB)
     |████████████████████████████████| 409kB 30.1MB/s eta 0:00:01
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Collecting toml
  Downloading https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/ed/d6/2afc375a8d55b8be879d6b4986d4f69f01115e795e36827fd3a40166028b/typing_extensions-4.3.0-py3-none-any.whl
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/d3/91/4df247dd4da18b72b5bbabe1fa2b85029c34e1d6f0afdd6329d15d6bf2b5/importlib_resources-5.9.0-py3-none-any.whl
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Collecting etils[epath]
  Downloading https://files.pythonhosted.org/packages/6b/f0/d717858522d20a4493ea93368a6a737ac7db791e199b07524a41982053f7/etils-0.6.0-py3-none-any.whl (98kB)
     |████████████████████████████████| 102kB 31.2MB/s ta 0:00:01
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Collecting zipp>=3.1.0; python_version < "3.10"
  Downloading https://files.pythonhosted.org/packages/f0/36/639d6742bcc3ffdce8b85c31d79fcfae7bb04b95f0e5c4c6f8b206a038cc/zipp-3.8.1-py3-none-any.whl
ERROR: tensorflow-metadata 0.14.0 has requirement protobuf<4,>=3.7, but you'll have protobuf 4.21.4 which is incompatible.
Installing collected packages: protobuf, toml, typing-extensions, zipp, importlib-resources, etils, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed etils-0.6.0 importlib-resources-5.9.0 protobuf-4.21.4 tfds-nightly-4.6.0.dev202207290046 toml-0.10.2 typing-extensions-4.3.0 zipp-3.8.1
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/db/27/6754ced3dfcdc0507c24df31b5daa9acfa6357f083b355081781fa040404/tensorflow-2.9.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (511.7MB)
     |████████████████████▍           | 326.1MB 29.5MB/s eta 0:00:07     |████████████████████████████████| 511.7MB 27.7MB/s eta 0:00:01     |████████████████████▌           | 328.3MB 29.5MB/s eta 0:00:07     |████████████████████▊           | 330.6MB 29.5MB/s eta 0:00:07     |█████████████████████           | 334.2MB 29.5MB/s eta 0:00:07     |█████████████████████▎          | 340.7MB 32.7MB/s eta 0:00:06     |██████████████████████          | 351.5MB 32.7MB/s eta 0:00:05     |██████████████████████▍         | 358.5MB 32.7MB/s eta 0:00:05     |██████████████████████▋         | 361.4MB 32.7MB/s eta 0:00:05     |██████████████████████▉         | 365.3MB 8.6MB/s eta 0:00:17     |███████████████████████         | 366.1MB 8.6MB/s eta 0:00:17     |███████████████████████         | 366.9MB 8.6MB/s eta 0:00:17     |███████████████████████▏        | 370.9MB 8.6MB/s eta 0:00:17     |███████████████████████▍        | 373.5MB 8.6MB/s eta 0:00:17     |████████████████████████▎       | 387.5MB 16.5MB/s eta 0:00:08     |████████████████████████▎       | 388.6MB 16.5MB/s eta 0:00:08     |████████████████████████▋       | 394.3MB 16.5MB/s eta 0:00:08     |████████████████████████▊       | 396.2MB 16.5MB/s eta 0:00:08     |█████████████████████████       | 401.1MB 26.0MB/s eta 0:00:05     |█████████████████████████▎      | 404.8MB 26.0MB/s eta 0:00:05     |█████████████████████████▍      | 406.1MB 26.0MB/s eta 0:00:05     |█████████████████████████▉      | 413.2MB 26.0MB/s eta 0:00:04     |███████████████████████████     | 432.6MB 6.0MB/s eta 0:00:14     |███████████████████████████▍    | 437.4MB 6.0MB/s eta 0:00:13     |███████████████████████████▋    | 441.3MB 35.0MB/s eta 0:00:03     |███████████████████████████▉    | 445.2MB 35.0MB/s eta 0:00:02     |████████████████████████████    | 446.4MB 35.0MB/s eta 0:00:02     |████████████████████████████    | 447.7MB 35.0MB/s eta 0:00:02     |████████████████████████████    | 448.9MB 35.0MB/s eta 0:00:02     |████████████████████████████▍   | 454.8MB 35.0MB/s eta 0:00:02     |████████████████████████████▊   | 460.1MB 35.0MB/s eta 0:00:02     |████████████████████████████▉   | 461.2MB 35.0MB/s eta 0:00:02     |█████████████████████████████   | 463.4MB 21.2MB/s eta 0:00:03     |█████████████████████████████▏  | 465.6MB 21.2MB/s eta 0:00:03     |█████████████████████████████▍  | 470.3MB 21.2MB/s eta 0:00:02     |█████████████████████████████▊  | 475.2MB 21.2MB/s eta 0:00:02     |██████████████████████████████▍ | 485.9MB 7.6MB/s eta 0:00:04     |██████████████████████████████▋ | 489.2MB 7.6MB/s eta 0:00:03     |██████████████████████████████▋ | 490.2MB 7.6MB/s eta 0:00:03     |██████████████████████████████▉ | 493.6MB 7.6MB/s eta 0:00:03     |███████████████████████████████▏| 498.3MB 7.6MB/s eta 0:00:02     |███████████████████████████████▌| 503.0MB 7.6MB/s eta 0:00:02     |███████████████████████████████▉| 509.5MB 27.7MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: setuptools in /opt/conda/lib/python3.7/site-packages (from tensorflow) (41.4.0)
Collecting protobuf<3.20,>=3.9.2
  Downloading https://files.pythonhosted.org/packages/03/6b/12b307892ef5e9f4a1a92f5996922561c453540f5ce22a09038d2486b451/protobuf-3.19.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1MB)
     |████████████████████████████████| 1.1MB 32.7MB/s eta 0:00:01
Collecting absl-py>=1.0.0
  Downloading https://files.pythonhosted.org/packages/a5/b8/fc74a554a6fc7f26744c883ebfe405cf49c1f1320f13ee874aee47c70e1d/absl_py-1.2.0-py3-none-any.whl (123kB)
     |████████████████████████████████| 133kB 55.7MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (3.1.0)
Requirement already satisfied, skipping upgrade: typing-extensions>=3.6.6 in /root/.local/lib/python3.7/site-packages (from tensorflow) (4.3.0)
Collecting tensorflow-io-gcs-filesystem>=0.23.1
  Downloading https://files.pythonhosted.org/packages/02/e2/e52124db811cac83d1773efd3c1e456db3aedb7974a5a4c431126bc2da79/tensorflow_io_gcs_filesystem-0.26.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.4MB)
     |████████████████████████████████| 2.4MB 27.4MB/s eta 0:00:01
Collecting tensorflow-estimator<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/61/e1/a72ec68403d91ba433018db58859fd4706642aa9d0fb44ff778934fc4c2c/tensorflow_estimator-2.9.0-py2.py3-none-any.whl (438kB)
     |████████████████████████████████| 440kB 31.5MB/s eta 0:00:01
Collecting grpcio<2.0,>=1.24.3
  Downloading https://files.pythonhosted.org/packages/10/82/cfe40a55c28b487fe0d15d9afef68551fe90a7bd4e3b04120321f300e22b/grpcio-1.48.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.6MB)
     |████████████████████████████████| 4.6MB 17.4MB/s eta 0:00:01     |██████████████████████████▊     | 3.8MB 17.4MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Collecting tensorboard<2.10,>=2.9
  Downloading https://files.pythonhosted.org/packages/ee/0d/23812e6ce63b3d87c39bc9fee83e28c499052fa83fddddd7daea21a6d620/tensorboard-2.9.1-py3-none-any.whl (5.8MB)
     |████████████████████████████████| 5.8MB 55.3MB/s eta 0:00:01     |███████████████████████▊        | 4.3MB 55.3MB/s eta 0:00:01
Collecting astunparse>=1.6.0
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Collecting keras<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/ff/ff/f25909606aed26981a8bd6d263f89d64a20ca5e5316e6aafb4c75d9ec8ae/keras-2.9.0-py2.py3-none-any.whl (1.6MB)
     |████████████████████████████████| 1.6MB 39.9MB/s eta 0:00:01     |██████████████████████████▏     | 1.3MB 39.9MB/s eta 0:00:01
Collecting keras-preprocessing>=1.1.1
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 48.4MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.1.8)
Requirement already satisfied, skipping upgrade: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.12.0)
Collecting libclang>=13.0.0
  Downloading https://files.pythonhosted.org/packages/ab/2f/c6f380aec0b064bccbd81141fecba9862b5634c838f13fff727adc84ceb9/libclang-14.0.1-py2.py3-none-manylinux1_x86_64.whl (14.5MB)
     |████████████████████████████████| 14.5MB 23.5MB/s eta 0:00:01    |██▊                             | 1.2MB 23.5MB/s eta 0:00:01     |█████                           | 2.3MB 23.5MB/s eta 0:00:01     |█████████████████▋              | 8.0MB 23.5MB/s eta 0:00:01
Collecting numpy>=1.20
  Downloading https://files.pythonhosted.org/packages/6d/ad/ff3b21ebfe79a4d25b4a4f8e5cf9fd44a204adb6b33c09010f566f51027a/numpy-1.21.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7MB)
     |████████████████████████████████| 15.7MB 28.0MB/s eta 0:00:01    |█████████▉                      | 4.8MB 28.0MB/s eta 0:00:01     |████████████████████████████▏   | 13.8MB 28.0MB/s eta 0:00:01     |██████████████████████████████▏ | 14.8MB 28.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: wrapt>=1.11.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.11.2)
Collecting flatbuffers<2,>=1.12
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting packaging
  Downloading https://files.pythonhosted.org/packages/05/8e/8de486cbd03baba4deef4142bd643a3e7bbe954a784dc1bb17142572d127/packaging-21.3-py3-none-any.whl (40kB)
     |████████████████████████████████| 40kB 40.5MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: gast<=0.4.0,>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.2.2)
Requirement already satisfied, skipping upgrade: h5py>=2.9.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (2.9.0)
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/e0/68/e8ecfac5dd594b676c23a7f07ea34c197d7d69b3313afdf8ac1b0a9905a2/tensorboard_plugin_wit-1.8.1-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 37.9MB/s eta 0:00:01
Collecting google-auth<3,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/7b/17/0b14f55fc8ff002b92e2deb796dd9e28a65ca1a6272d9d844e99051afb67/google_auth-2.9.1-py2.py3-none-any.whl (167kB)
     |████████████████████████████████| 174kB 38.0MB/s eta 0:00:01
Collecting werkzeug>=1.0.1
  Downloading https://files.pythonhosted.org/packages/c0/93/d6d60870e47162ea6a1bbdd787649eea776b2a70618dd66ed87cb2238543/Werkzeug-2.2.1-py3-none-any.whl (232kB)
     |████████████████████████████████| 235kB 16.7MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: wheel>=0.26 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (0.33.6)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (3.1.1)
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
     |████████████████████████████████| 4.9MB 38.6MB/s eta 0:00:01     |█████████████████▉              | 2.7MB 38.6MB/s eta 0:00:01     |█████████████████████████       | 3.8MB 38.6MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (2.22.0)
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.7/site-packages (from packaging->tensorflow) (2.4.6)
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 55.5MB/s eta 0:00:01
Collecting cachetools<6.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/68/aa/5fc646cae6e997c3adf3b0a7e257cda75cff21fcba15354dffd67789b7bb/cachetools-5.2.0-py3-none-any.whl
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/49/97/fa78e3d2f65c02c8e1268b9aba606569fe97f6c8f7c2d74394553347c145/rsa-4.9-py3-none-any.whl
Collecting MarkupSafe>=2.1.1
  Downloading https://files.pythonhosted.org/packages/9f/83/b221ce5a0224f409b9f02b0dc6cb0b921c46033f4870d64fa3e8a96af701/MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (1.24.2)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (3.0.4)
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl
Collecting pyasn1<0.5.0,>=0.4.6
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 27.8MB/s eta 0:00:01
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/1d/46/5ee2475e1b46a26ca0fa10d3c1d479577fde6ee289f8c6aa6d7ec33e31fd/oauthlib-3.2.0-py3-none-any.whl (151kB)
     |████████████████████████████████| 153kB 50.6MB/s eta 0:00:01
Installing collected packages: protobuf, absl-py, tensorflow-io-gcs-filesystem, tensorflow-estimator, grpcio, tensorboard-plugin-wit, pyasn1, pyasn1-modules, cachetools, rsa, google-auth, MarkupSafe, werkzeug, tensorboard-data-server, numpy, oauthlib, requests-oauthlib, google-auth-oauthlib, tensorboard, astunparse, keras, keras-preprocessing, libclang, flatbuffers, packaging, tensorflow
  Found existing installation: protobuf 4.21.4
    Uninstalling protobuf-4.21.4:
      Successfully uninstalled protobuf-4.21.4
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed MarkupSafe-2.1.1 absl-py-1.2.0 astunparse-1.6.3 cachetools-5.2.0 flatbuffers-1.12 google-auth-2.9.1 google-auth-oauthlib-0.4.6 grpcio-1.48.0 keras-2.9.0 keras-preprocessing-1.1.2 libclang-14.0.1 numpy-1.21.6 oauthlib-3.2.0 packaging-21.3 protobuf-3.19.4 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.1 rsa-4.9 tensorboard-2.9.1 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.1 tensorflow-2.9.1 tensorflow-estimator-2.9.0 tensorflow-io-gcs-filesystem-0.26.0 werkzeug-2.2.1
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow-datasets
  Downloading https://files.pythonhosted.org/packages/05/ae/b6efc66bf6276265d813e12a895b05bc3533092d107ca57c8ecbf4c7c963/tensorflow_datasets-4.6.0-py3-none-any.whl (4.3MB)
     |████████████████████████████████| 4.3MB 4.8MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: numpy in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (1.21.6)
Requirement already satisfied, skipping upgrade: six in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.0)
Requirement already satisfied, skipping upgrade: absl-py in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (1.2.0)
Requirement already satisfied, skipping upgrade: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied, skipping upgrade: importlib-resources; python_version < "3.9" in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (5.9.0)
Requirement already satisfied, skipping upgrade: etils[epath] in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (0.6.0)
Requirement already satisfied, skipping upgrade: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied, skipping upgrade: typing-extensions; python_version < "3.8" in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (4.3.0)
Requirement already satisfied, skipping upgrade: toml in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (0.10.2)
Requirement already satisfied, skipping upgrade: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied, skipping upgrade: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied, skipping upgrade: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied, skipping upgrade: protobuf>=3.12.2 in /root/.local/lib/python3.7/site-packages (from tensorflow-datasets) (3.19.4)
Requirement already satisfied, skipping upgrade: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied, skipping upgrade: zipp>=3.1.0; python_version < "3.10" in /root/.local/lib/python3.7/site-packages (from importlib-resources; python_version < "3.9"->tensorflow-datasets) (3.8.1)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied, skipping upgrade: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Installing collected packages: tensorflow-datasets
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed tensorflow-datasets-4.6.0
Note: you may need to restart the kernel to use updated packages.

After the above installations have finished be sure to restart the kernel. You can do this by going to Kernel > Restart.

In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub

# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')
In [2]:
# TODO: Make all other necessary imports.
import time
import numpy as np
import matplotlib.pyplot as plt
In [3]:
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [5]:
# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()

dataset, dataset_info= tfds.load('oxford_flowers102:2.1.1', as_supervised=True, with_info=True)

# TODO: Create a training set, a validation set and a test set.
training, testing, validation = dataset['train'], dataset['test'], dataset['validation']

Explore the Dataset

In [6]:
# TODO: Get the number of examples in each set from the dataset info.
num_classes= dataset_info.features['label'].num_classes
train_examples = dataset_info.splits['train'].num_examples
test_examples = dataset_info.splits['test'].num_examples
validation_examples = dataset_info.splits['validation'].num_examples
print('The Dataset has a total of:')

print('\u2022 {:,} train images'.format(train_examples))
print('\u2022 {:,} test images'.format(test_examples))
print('\u2022 {:,} validation images'.format(validation_examples))
# TODO: Get the number of classes in the dataset from the dataset info.
print('\u2022 {:,} classes'.format(num_classes))
The Dataset has a total of:
• 1,020 train images
• 6,149 test images
• 1,020 validation images
• 102 classes
In [7]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for i, (image, label) in enumerate(training.take(3)):
    image = image.numpy()
    label = label.numpy()
    print('\u2022 Image {:} has shape of {:} and label of {:} '.format(i, str(image.shape), label))
• Image 0 has shape of (500, 667, 3) and label of 72 
• Image 1 has shape of (500, 666, 3) and label of 84 
• Image 2 has shape of (670, 500, 3) and label of 70 
In [8]:
# TODO: Plot 1 image from the training set. 
for image, label in training.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)
plt.title(label)
plt.show()
# Set the title of the plot to the corresponding image label. 

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [11]:
class_names = dataset_info.features['label'].names
class_names
Out[11]:
['pink primrose',
 'hard-leaved pocket orchid',
 'canterbury bells',
 'sweet pea',
 'english marigold',
 'tiger lily',
 'moon orchid',
 'bird of paradise',
 'monkshood',
 'globe thistle',
 'snapdragon',
 "colt's foot",
 'king protea',
 'spear thistle',
 'yellow iris',
 'globe-flower',
 'purple coneflower',
 'peruvian lily',
 'balloon flower',
 'giant white arum lily',
 'fire lily',
 'pincushion flower',
 'fritillary',
 'red ginger',
 'grape hyacinth',
 'corn poppy',
 'prince of wales feathers',
 'stemless gentian',
 'artichoke',
 'sweet william',
 'carnation',
 'garden phlox',
 'love in the mist',
 'mexican aster',
 'alpine sea holly',
 'ruby-lipped cattleya',
 'cape flower',
 'great masterwort',
 'siam tulip',
 'lenten rose',
 'barbeton daisy',
 'daffodil',
 'sword lily',
 'poinsettia',
 'bolero deep blue',
 'wallflower',
 'marigold',
 'buttercup',
 'oxeye daisy',
 'common dandelion',
 'petunia',
 'wild pansy',
 'primula',
 'sunflower',
 'pelargonium',
 'bishop of llandaff',
 'gaura',
 'geranium',
 'orange dahlia',
 'pink-yellow dahlia?',
 'cautleya spicata',
 'japanese anemone',
 'black-eyed susan',
 'silverbush',
 'californian poppy',
 'osteospermum',
 'spring crocus',
 'bearded iris',
 'windflower',
 'tree poppy',
 'gazania',
 'azalea',
 'water lily',
 'rose',
 'thorn apple',
 'morning glory',
 'passion flower',
 'lotus',
 'toad lily',
 'anthurium',
 'frangipani',
 'clematis',
 'hibiscus',
 'columbine',
 'desert-rose',
 'tree mallow',
 'magnolia',
 'cyclamen',
 'watercress',
 'canna lily',
 'hippeastrum',
 'bee balm',
 'ball moss',
 'foxglove',
 'bougainvillea',
 'camellia',
 'mallow',
 'mexican petunia',
 'bromelia',
 'blanket flower',
 'trumpet creeper',
 'blackberry lily']
In [12]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in training.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)
plt.title(class_names[label])
plt.show()

Create Pipeline

In [13]:
# TODO: Create a pipeline for each set.

batch_size = 32
image_size = 224

num_training_examples = test_examples
print(num_training_examples)
print(testing)
@tf.autograph.experimental.do_not_convert
def format_image(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image, label


training_batches = testing.shuffle(num_training_examples//8).map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation.map(format_image).batch(batch_size).prefetch(1)
testing_batches = training.map(format_image).batch(batch_size).prefetch(1)
6149
<PrefetchDataset element_spec=(TensorSpec(shape=(None, None, 3), dtype=tf.uint8, name=None), TensorSpec(shape=(), dtype=tf.int64, name=None))>

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [14]:
# TODO: Build and train your network.

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))

feature_extractor.trainable = False

#initializer = tf.keras.initializers.GlorotUniform(seed = 42)

model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(num_classes, activation = 'softmax')
])

model.summary()
WARNING:tensorflow:AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f7564502610>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f7564502610>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f7564502610>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
In [15]:
print('Is there a GPU Available:', tf.test.is_gpu_available())
WARNING:tensorflow:From <ipython-input-15-32e03adf40fd>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
WARNING:tensorflow:From <ipython-input-15-32e03adf40fd>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
Is there a GPU Available: False
In [24]:
import signal

from contextlib import contextmanager

import requests


DELAY = INTERVAL = 4 * 60  # interval time in seconds
MIN_DELAY = MIN_INTERVAL = 2 * 60
KEEPALIVE_URL = "https://nebula.udacity.com/api/v1/remote/keep-alive"
TOKEN_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/keep_alive_token"
TOKEN_HEADERS = {"Metadata-Flavor":"Google"}


def _request_handler(headers):
    def _handler(signum, frame):
        requests.request("POST", KEEPALIVE_URL, headers=headers)
    return _handler


@contextmanager
def active_session(delay=DELAY, interval=INTERVAL):
    """
    Example:

    from workspace_utils import active session

    with active_session():
        # do long-running work here
    """
    token = requests.request("GET", TOKEN_URL, headers=TOKEN_HEADERS).text
    headers = {'Authorization': "STAR " + token}
    delay = max(delay, MIN_DELAY)
    interval = max(interval, MIN_INTERVAL)
    original_handler = signal.getsignal(signal.SIGALRM)
    try:
        signal.signal(signal.SIGALRM, _request_handler(headers))
        signal.setitimer(signal.ITIMER_REAL, delay, interval)
        yield
    finally:
        signal.signal(signal.SIGALRM, original_handler)
        signal.setitimer(signal.ITIMER_REAL, 0)


def keep_awake(iterable, delay=DELAY, interval=INTERVAL):
    """
    Example:

    from workspace_utils import keep_awake

    for i in keep_awake(range(5)):
        # do iteration with lots of work here
    """
    with active_session(delay, interval): yield from iterable
In [25]:
model.compile(optimizer = "adam",
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

EPOCHS = 15

from keras.callbacks import CSVLogger

csv_logger = CSVLogger("model_history_log.csv", append=True)
save_best = tf.keras.callbacks.ModelCheckpoint('./best_model.h5',
                                              monitor='val_loss',
                                              save_best_only = True)


with active_session():
    history = model.fit(training_batches,
                    epochs=EPOCHS,
                    validation_data=validation_batches,
                   callbacks=[csv_logger,save_best])
Epoch 1/15
WARNING:tensorflow:AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f75362a24d0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f75362a24d0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f75362a24d0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
193/193 [==============================] - ETA: 0s - loss: 1.9501 - accuracy: 0.5986WARNING:tensorflow:AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f752684eb00> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f752684eb00> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f752684eb00> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
193/193 [==============================] - 150s 749ms/step - loss: 1.9501 - accuracy: 0.5986 - val_loss: 1.0177 - val_accuracy: 0.7765
Epoch 2/15
193/193 [==============================] - 145s 747ms/step - loss: 0.5414 - accuracy: 0.9047 - val_loss: 0.6419 - val_accuracy: 0.8598
Epoch 3/15
193/193 [==============================] - 142s 734ms/step - loss: 0.3116 - accuracy: 0.9494 - val_loss: 0.5190 - val_accuracy: 0.8794
Epoch 4/15
193/193 [==============================] - 147s 758ms/step - loss: 0.2073 - accuracy: 0.9694 - val_loss: 0.4678 - val_accuracy: 0.8824
Epoch 5/15
193/193 [==============================] - 144s 743ms/step - loss: 0.1472 - accuracy: 0.9821 - val_loss: 0.4286 - val_accuracy: 0.8951
Epoch 6/15
193/193 [==============================] - 144s 740ms/step - loss: 0.1119 - accuracy: 0.9878 - val_loss: 0.4184 - val_accuracy: 0.8971
Epoch 7/15
193/193 [==============================] - 142s 733ms/step - loss: 0.0844 - accuracy: 0.9954 - val_loss: 0.3981 - val_accuracy: 0.9010
Epoch 8/15
193/193 [==============================] - 145s 747ms/step - loss: 0.0664 - accuracy: 0.9967 - val_loss: 0.3796 - val_accuracy: 0.9020
Epoch 9/15
193/193 [==============================] - 146s 753ms/step - loss: 0.0533 - accuracy: 0.9984 - val_loss: 0.3735 - val_accuracy: 0.9039
Epoch 10/15
193/193 [==============================] - 145s 746ms/step - loss: 0.0442 - accuracy: 0.9990 - val_loss: 0.3663 - val_accuracy: 0.9049
Epoch 11/15
193/193 [==============================] - 146s 752ms/step - loss: 0.0363 - accuracy: 0.9997 - val_loss: 0.3671 - val_accuracy: 0.9039
Epoch 12/15
193/193 [==============================] - 147s 757ms/step - loss: 0.0304 - accuracy: 0.9998 - val_loss: 0.3541 - val_accuracy: 0.9049
Epoch 13/15
193/193 [==============================] - 146s 753ms/step - loss: 0.0260 - accuracy: 0.9998 - val_loss: 0.3599 - val_accuracy: 0.9010
Epoch 14/15
193/193 [==============================] - 145s 749ms/step - loss: 0.0231 - accuracy: 0.9997 - val_loss: 0.3533 - val_accuracy: 0.9108
Epoch 15/15
193/193 [==============================] - 146s 751ms/step - loss: 0.0200 - accuracy: 0.9997 - val_loss: 0.3521 - val_accuracy: 0.9088
In [26]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(figsize=(12,9), ncols=2)
ax1.plot(history.history['loss'], label = 'Training Loss')
ax1.plot(history.history['val_loss'], label = 'Validation Loss')
ax1.set_title('Training and Validation Loss')
ax1.legend()
ax2.plot(history.history['accuracy'], label = 'Training Accuracy')
ax2.plot(history.history['val_accuracy'], label = 'Validation Accuracy')
ax2.set_title('Training and Validation Accuracy')
ax2.legend()
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [27]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)
print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
32/32 [==============================] - 21s 637ms/step - loss: 0.4174 - accuracy: 0.8794

Loss on the TEST Set: 0.417
Accuracy on the TEST Set: 87.941%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [28]:
# TODO: Save your trained model as a Keras model.
model.save('saved_model/my_model')
WARNING:tensorflow:AutoGraph could not transform <function trace_model_call.<locals>._wrapped_model at 0x7f75360e4290> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function trace_model_call.<locals>._wrapped_model at 0x7f75360e4290> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function trace_model_call.<locals>._wrapped_model at 0x7f75360e4290> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function canonicalize_signatures.<locals>.signature_wrapper at 0x7f7536108320> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function canonicalize_signatures.<locals>.signature_wrapper at 0x7f7536108320> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function canonicalize_signatures.<locals>.signature_wrapper at 0x7f7536108320> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function KerasLayer._call_loss_if_trainable.<locals>.<lambda> at 0x7f7536a01c20> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function KerasLayer._call_loss_if_trainable.<locals>.<lambda> at 0x7f7536a01c20> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function KerasLayer._call_loss_if_trainable.<locals>.<lambda> at 0x7f7536a01c20> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
INFO:tensorflow:Assets written to: saved_model/my_model/assets
INFO:tensorflow:Assets written to: saved_model/my_model/assets

Load the Keras Model

Load the Keras model you saved above.

In [29]:
# TODO: Load the Keras model
loaded_model = tf.keras.models.load_model('saved_model/my_model',custom_objects = {'KerasLayer':hub.KerasLayer})
loaded_model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [30]:
# TODO: Create the process_image function
# TODO: Create the process_image function
@tf.autograph.experimental.do_not_convert
def process_image(image):
    image = tf.convert_to_tensor(image, tf.float32)
    image = tf.image.resize(image, (224, 224))
    image /= 255
    image = image.numpy()
    image = image.reshape((224, 224, 3))
    image = image.astype('float32')
    return image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [31]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [36]:
# TODO: Create the predict function
@tf.autograph.experimental.do_not_convert
def predict(image_path, model, k_classes):
    img = Image.open(image_path)
    img = np.asarray(img)
    img = process_image(img)
    img = tf.expand_dims(img, axis = 0)
    probs = model.predict(img)
    values, indices = tf.nn.top_k(probs,k = k_classes)
    probs = list(values.numpy()[0])
    classes = list(indices.numpy()[0])
    return classes, probs

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [37]:
# TODO: Plot the input image along with the top 5 classes
import os 
path = './test_images/'
imgs = os.listdir(path)
imgs = [os.path.join(path,image) for image in imgs]
print(imgs)
for image_path in imgs:
    top_5_classes, probabilities = predict(image_path, loaded_model, 5)
    #probabilities = np.argpartition(probabilities, -4)[-4:]
    np_classes = np.array(class_names)
    print(probabilities, top_5_classes)
    im = Image.open(image_path)
    test_image = np.asarray(im)
    probabilities = probabilities / np.sum(probabilities)

    fig, ax1 = plt.subplots(figsize=(12,9), ncols=2, nrows=1)
    ax1[0].imshow(test_image)
    ax1[0].axis('off')
    ax1[0].set_title(image_path.split('/')[2])
    ax1[1].barh(np.arange(5), probabilities,color='maroon')
    ax1[1].set_aspect(0.1)
    ax1[1].set_yticks(np.arange(5))
    ax1[1].set_yticklabels(np_classes[top_5_classes], size='small');
    ax1[1].set_title('Class Probability')
    ax1[1].set_xlim(0, 1.1)
    plt.tight_layout()
    plt.show()
['./test_images/orange_dahlia.jpg', './test_images/wild_pansy.jpg', './test_images/hard-leaved_pocket_orchid.jpg', './test_images/cautleya_spicata.jpg']
1/1 [==============================] - 0s 45ms/step
[0.9901142, 0.00311968, 0.0024334248, 0.0017630706, 0.0007156034] [58, 4, 40, 65, 82]
1/1 [==============================] - 0s 47ms/step
[0.9999242, 1.8207156e-05, 9.460714e-06, 6.4154347e-06, 5.205768e-06] [51, 52, 18, 85, 33]
1/1 [==============================] - 0s 45ms/step
[0.99976355, 0.00018564722, 1.6534252e-05, 7.753721e-06, 7.514741e-06] [1, 17, 76, 93, 6]
1/1 [==============================] - 0s 45ms/step
[0.99822885, 0.00028676438, 0.00019084635, 0.00018190933, 0.00013433058] [60, 93, 23, 83, 42]
In [ ]:
 
In [ ]: